<template>
  <!--  <div class="index-header" :style="bgColor?'background-color: transparent;':'background-color: white;'">-->
  <div class="index-header" :style="hasBgColor?'background-color: #fff;':'background-color: transparent;'">
    <!--    <span v-if="showBanner">显示banner</span>-->
    <el-menu
        :text-color="textColor"
        :default-active="activeIndex"
        mode="horizontal"
        @select="handleSelect"
        :style="showBorderBottom?'':'border-bottom:none'"
    >
      <!--      style="background-color: transparent;"-->
      <el-menu-item @click="toIndex">首页</el-menu-item>

      <el-menu-item>
        <div class="input-box">
          <el-input
              v-model="keyword"
              style="width: 340px;height: 45px"
              placeholder="不是哥们 面试造火箭 你入职真去打螺丝啊？"
              clearable
              v-if="hasInput"
          />
          <el-button type="primary" size="large" @click="search()" v-if="hasInput">搜索</el-button>

        </div>
      </el-menu-item>
      <!--      <el-menu-item v-if="userInfo.userId" index="/space/home" class="avatar_blk">-->
      <el-menu-item v-if="userInfo.userId" class="avatar_blk">
        <el-popover
            placement="top"
            :width="300"
            trigger="hover"
            @show="loadUserStat"
        >
          <div class="nickname" @click="toSpace">{{ userInfo.nickname }}</div>
          <div class="summary-box">
            <div class="relation">
              <div class="relation-item">
                <div class="count">{{ userStat.followCount }}</div>
                <div>关注</div>
              </div>
              <div class="relation-item">
                <div class="count">{{ userStat.fansCount }}</div>
                <div>粉丝</div>
              </div>
              <div class="relation-item">
                <div class="count">{{ userStat.dynamicCount }}</div>
                <div>动态</div>
              </div>
            </div>
            <div class="operation">
              <el-row @click="toPersonInfo()">
                <el-col :span="4">
                  <el-icon>
                    <User/>
                  </el-icon>
                </el-col>
                <el-col :span="18">
                  个人中心
                </el-col>
                <el-col :span="2">
                  <el-icon>
                    <ArrowRight/>
                  </el-icon>
                </el-col>
              </el-row>
              <!--              <el-row>-->
              <!--                <el-col :span="4">-->
              <!--                  <el-icon><UploadFilled /></el-icon>-->
              <!--                </el-col>-->
              <!--                <el-col :span="18">-->
              <!--                  投稿管理-->
              <!--                </el-col>-->
              <!--                <el-col :span="2">-->
              <!--                  <el-icon><ArrowRight /></el-icon>-->
              <!--                </el-col>-->
              <!--              </el-row>-->
              <el-divider/>
              <el-row @click="handleLogout">
                <el-col :span="4">
                  <el-icon>
                    <CircleClose/>
                  </el-icon>
                </el-col>
                <el-col :span="18">
                  退出登录
                </el-col>

              </el-row>
            </div>
          </div>
          <template #reference>
            <el-avatar @click="toSpace()" class="avatar" :size="50" :src="userInfo.userAvatar"/>
          </template>
        </el-popover>

      </el-menu-item>
      <el-menu-item v-else class="avatar_blk">
        <div class="no-login" @click="handleLogin">登录</div>
      </el-menu-item>


      <!--      -->
      <el-menu-item @click="toMessage" v-if="userInfo.userId">
        <!--        <el-popover-->
        <!--            placement="top-start"-->
        <!--            title="消息"-->
        <!--            :width="200"-->
        <!--            trigger="hover"-->
        <!--        >-->
        <!--          <el-row>回复我的</el-row>-->
        <!--          <el-row>@我的</el-row>-->
        <!--          <el-row>收到的赞</el-row>-->
        <!--          <el-row>我的消息</el-row>-->
        <!--          <template #reference>-->
        <!--&lt;!&ndash;            <div class="icon"><el-icon><Message /></el-icon></div>&ndash;&gt;-->
        <!--&lt;!&ndash;            <el-icon><Message /></el-icon>&ndash;&gt;-->
        <!--            <div class="item-box-em-sl">-->
        <!--              <div class="text">-->
        <!--                <el-icon><Message /></el-icon>-->
        <!--              </div>-->
        <!--              <div class="text">消息</div>-->
        <!--            </div>-->

        <!--          </template>-->
        <!--        </el-popover>-->
        <div class="item-box-em-sl">
          <div class="text">
            <el-icon>
              <Message/>
            </el-icon>
          </div>
          <div class="text">消息</div>
        </div>
      </el-menu-item>
      <el-menu-item @click="toMessage" v-else>
        消息
      </el-menu-item>
      <el-menu-item @click="toDynamic">
        <div class="item-box-em-sl">
          <div class="text">
            <el-icon>
              <Promotion/>
            </el-icon>
          </div>
          <div class="text">动态</div>
        </div>
      </el-menu-item>
      <el-menu-item @click="toSave">
        <div class="item-box-em-sl">
          <div class="text">
            <el-icon>
              <StarFilled/>
            </el-icon>
          </div>
          <div class="text">收藏</div>
        </div>
      </el-menu-item>
      <el-menu-item @click="toHistory">
        <div class="item-box-em-sl">
          <div class="text">
            <el-icon>
              <Clock/>
            </el-icon>
          </div>
          <div class="text">历史</div>
        </div>
      </el-menu-item>
      <el-menu-item @click="toCreate" style="width: 60px">
        <el-button type="primary">投稿</el-button>
      </el-menu-item>

    </el-menu>
  </div>
</template>
<script setup>
import {onMounted, ref} from 'vue'

const activeIndex = ref('1')
const handleSelect = (key, keyPath) => {
  console.log(key, keyPath)
}
// 是否展示下边框

// let props = withDefaults(defineProps(),{
//   showBorderBottom:()=> true
// })
const props = defineProps({
  showBorderBottom: {
    type: Boolean,
    default: true
  },
  hasInput: {
    type: Boolean,
    default: true
  },
  bgColor: {
    type: Boolean,
    default: true
  }
})


// const circleUrl = ref("/img/avatar.webp")


// 登录
/**
 * 用户信息
 */
// const userInfo = ref({
//   id:1,
//   nickname:'甜久SaltWaterRoom',
//   avatar:"/img/avatar.webp",
//   followCount:123,
//   fansCount:666,
//   dynamicCount:5
// })
const userInfo = ref({})

const userStat = ref({})

import emitter from "@/utils/emitter.js";

const handleLogin = () => {
  console.log("登录")
  emitter.emit("showLogin", true)
  return true;
}

import {getUserInfo, getUserStat, logout} from "@/api/api.js";

const handleLogout = async () => {
  console.log("退出登录")
  const res = await logout();
  console.log(res)
  if(res.code !== 200){
    ElMessage.error("退出登录失败")
  }
  console.log("更新界面")
  userInfo.value = {};
  console.log("删除本地存储信息")
  localStorage.removeItem("token")
  localStorage.removeItem("userId")
  console.log("删除pinia信息")
  userStore.setUserInfo({});

  console.log(router.currentRoute.value)
  const currentPath = router.currentRoute.value.fullPath
  if (currentPath !== '/') {
    console.log("当前页面不是首页，跳转至首页")
    router.push("/")
  }
  console.log("退出登录完成，开始监听用户是否登录")
  emitter.on("userInfo", (val) => {
    userInfo.value = val;
  });
}
import {useUserStore} from "@/stores/userInfoStore.js";

const userStore = useUserStore();
onMounted(async () => {
  console.log("开始获取用户信息")
  userInfo.value = userStore.userInfo
  if (!userInfo.value.userId) {
    console.log("pinia中没有用户信息，尝试从本地存储中获取")
    const userId = localStorage.getItem("userId")
    if (userId) {
      console.log("userId获取成功，用户没有退出登录，开始重新获取数据")
      const {data} = await getUserInfo(userId)
      console.log(data)
      userInfo.value.userId = data.userId
      userInfo.value.userAvatar = data.userAvatar
      userInfo.value.nickname = data.nickname
      userStore.setUserInfo(userInfo.value)

      emitter.on("switchAvatar", (url) => {

        userInfo.value.userAvatar = url
      })
      return;
    }
  }


  console.log("已经从pinia中获取到用户信息，开始监听用户信息")
  emitter.on("userInfo", (info) => {
    console.log("登录状态下收到用户信息")
    console.log(info)
    userInfo.value = info;
  })
  emitter.on("switchAvatar", (url) => {
    console.log("登录状态下收到切换头像事件，url为：" + url)
    userInfo.value.userAvatar = url
  })
  emitter.on("test01", (val1, val2) => {
    console.log(val1, val2)
  })
})


const loadUserStat = async () => {
  // alert("loadUserStat")
  console.log("开始获取用户统计信息")
  const userId = userInfo.value.userId
  if(!userId){
    console.log("用户未登录，无法获取统计信息，return")
    return;
  }
  const res = await getUserStat(userId);
  console.log("用户统计信息为：")
  console.log(res.data)
  userStat.value.followCount = res.data.followCount
  userStat.value.fansCount = res.data.fansCount
  userStat.value.dynamicCount = res.data.dynamicCount
}

import {useRoute, useRouter} from "vue-router";
import {ArrowRight, CircleClose, User} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";


const router = useRouter()
const checkLogin = () => {
  console.log(userInfo.value.userId)
  return !(userInfo.value.userId === undefined && handleLogin());

}
const toIndex = () => {
  console.log("去首页")
  // if(!checkLogin()) return;
  // router.push("/")
  if (route.fullPath.includes('/video')) {
    window.open("/", '_blank');
  } else {
    router.push("/")
  }
}
const toMessage = () => {
  console.log("去消息页面")
  // if(!checkLogin()) return;
  if (route.fullPath.includes('/video')) {
    window.open("/message/mymessage", '_blank');
  } else {
    router.push("/message/mymessage")
  }
}
const toDynamic = () => {
  console.log("去动态页面")
  // if(!checkLogin()) return;
  if (route.fullPath.includes('/video')) {
    window.open("/dynamics", '_blank');
  } else {
    router.push("/dynamics")
  }

}
const route = useRoute()

const toSave = () => {
  console.log("去收藏页面")
  //if(!checkLogin()) return;
  // router.push("/space/save")
  console.log(route.fullPath)
  const userId = localStorage.getItem("userId")
  if (route.fullPath.includes('/video')) {
    window.open("/space/save/" + userId, '_blank');
  } else {
    router.push("/space/save/" + userId)
  }

}
const toHistory = () => {
  if (route.fullPath.includes('/video')) {
    window.open("/history", '_blank');
  } else {
    router.push("/history")
  }
  console.log("去历史页面")
  //if(!checkLogin()) return;

}
const toCreate = () => {
  console.log("去创作中心页面")
  if (route.fullPath.includes('/video')) {
    window.open("/create/index", '_blank');
  } else {
    router.push("/create/index")
  }
  //if(!checkLogin()) return;

}
const toSpace = () => {
  console.log("去我的主页页面")
  //if(!checkLogin()) return;
  // router.push("/space/home")
  console.log(userInfo.value)
  // router.push({
  //   name:'home',
  //   params:{
  //     userId: userInfo.value.userId
  //   }
  // })
  if (route.fullPath.includes('/video')) {
    window.open("/space/home/" + userInfo.value.userId, '_blank');
  } else {
    router.push("/space/home/" + userInfo.value.userId)
  }
}
const toPersonInfo = () => {
  console.log("去个人页面")
  if (route.fullPath.includes('/video')) {
    window.open("/account/setting", '_blank');
  } else {
    router.push("/account/setting")
  }
}


/* 搜索相关 */
const keyword = ref()
const search = () => {
  console.log("搜索")
  if (!keyword.value.trim()) {
    return
  }
  if (route.fullPath.includes('/video')) {
    window.open("/search?keyword=" + keyword.value, '_blank');
  } else {
    router.push({
      name: 'search',
      query: {
        keyword: keyword.value
      }
    })
  }
  // keyword.value = ''
}
/* 搜索相关结束 */


// /* 顶部banner */
//
// const showBanner = ref(false)
// onMounted(()=>{
//   emitter.on("hasBanner",(val)=>{
//     showBanner.value = val
//   })
//   console.log()
// })
// /* 顶部banner结束 */

// 是否显示背景颜色
const hasBgColor = ref(true)

const textColor = ref("black")

onMounted(() => {
  emitter.on("changeBgColor", ({color, hasColor}) => {
    textColor.value = color
    hasBgColor.value = hasColor
  })
  emitter.on("clearUserInfo", () => {
    userInfo.value = {}
  })
  // emitter.on("blackText",()=>{
  //
  // })
})


</script>
<style scoped lang="scss">
//.index-header{
//  height: 200px;
//  width: 100%;
//  background-color: blue;
//}
.index-header {
  padding-left: 20px;
  box-sizing: border-box;
  //background-color: transparent;
}

//.el-menu--horizontal > .el-menu-item:nth-child(1) {
//  margin-right: auto;
//}
.avatar {
  transition: all 0.3s linear;

}

.el-menu {
  background-color: transparent;
}

.el-menu--horizontal
.el-menu-item:not(.is-disabled):focus, .el-menu--horizontal .el-menu-item:not(.is-disabled):hover {
  background-color: transparent;
}


/*
.avatar_blk:hover .avatar{

  transform: translate(-20px,20px) scale(1.8);
}
//.avatar:hover{
//
//  transform: translate(-20px,20px) scale(1.8);
//}
*/
.nickname {
  text-align: center;
  margin-bottom: 20px;
  color: black;
  font-size: 18px;
  cursor: pointer;
}

.summary-box {
  width: 270px;
  //height: 20px;
  //background-color: green;
  .relation {
    width: 270px;
    height: 60px;
    display: flex;

    .relation-item {
      width: 90px;
      height: 100px;
      text-align: center;

      .count {
        color: black;
      }
    }
  }
}

.operation {
  cursor: pointer;
}

.el-row {
  margin-bottom: 20px;
}

.baseInfo {
  text-align: right;
  //color: red;
}

.no-login {
  width: 50px;
  height: 50px;
  text-align: center;
  line-height: 50px;
  color: white;
  background-color: #64bbff;
  border-radius: 50%;
}

.input-box {
  width: 870px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  padding-left: 460px;
}


//:deep(.el-tooltip__trigger){
//  width: 60px;
//  height: 60px !important;
//  display: flex !important;
//  flex-direction: column !important;
//  justify-content: center !important;
//}
.item-box-em-sl {
  //background-color: #ff0000;

  //width: 60px;
  height: 60px !important;
  display: flex !important;
  flex-direction: column !important;
  justify-content: center !important;
  //gap: 0
  .text {
    height: 20px;
    line-height: 20px
  }
}
</style>